import React, { useEffect, useState } from "react";
import { useProviderStore } from "../../../stores/useProviderStore";
import { useAgentStore } from "../../../stores/useAgentStore";
import { Input } from "../../ui/input";
import { Button } from "../../ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "../../ui/card";
import { Label } from "../../ui/label";
import { Switch } from "../../ui/switch";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "../../ui/select";
import { Textarea } from "../../ui/textarea";
import { Badge } from "../../ui/badge";
import { toastError, toastSuccess } from "@/components/ui/toasts";
import apiService from "../../../lib/api";

interface ProviderSettingsSectionProps {
	// No props needed for now, as it will use the Zustand store
}

export const ProviderSettingsSection: React.FC<
	ProviderSettingsSectionProps
> = () => {
	const {
		availableProviders,
		configuredProviders,
		loading,
		error,
		loadProviders,
		upsertProviderConfig,
		isProviderFullyConfigured,
	} = useProviderStore();

	const { agents, addAgent } = useAgentStore();

	const [editingProvider, setEditingProvider] = useState<string | null>(null);
	const [providerInputs, setProviderInputs] = useState<Record<string, string>>(
		{},
	);
	const [showCreateAgent, setShowCreateAgent] = useState<string | null>(null);
	const [agentForm, setAgentForm] = useState({
		name: "",
		model: "",
		preamble: "You are a helpful AI assistant.",
		baseUrl: "",
		tools: [] as string[],
		apiKey: "",
	});
	const [creatingAgent, setCreatingAgent] = useState(false);

	useEffect(() => {
		loadProviders();
	}, [loadProviders]);

	useEffect(() => {
		if (error) {
			toastError({ title: error });
		}
	}, [error]);

	const handleEditClick = (providerName: string) => {
		setEditingProvider(providerName);
		// Pre-fill inputs with existing configured values
		const currentConfig = configuredProviders[providerName] || {};
		setProviderInputs(currentConfig);
	};

	const handleInputChange = (key: string, value: string) => {
		setProviderInputs((prev) => ({
			...prev,
			[key]: value,
		}));
	};

	const handleSaveConfig = async (providerName: string) => {
		if (!editingProvider) return;

		const providerDetails = availableProviders.find(
			(p) => p.name === providerName,
		);
		if (!providerDetails) return;

		try {
			for (const configKey of providerDetails.metadata.config_keys) {
				const value = providerInputs[configKey.name];
				if (configKey.required && !value) {
					toastError({
						title: `Error: ${configKey.name} is required for ${providerDetails.display_name}`,
					});
					return;
				}
				if (value) {
					await upsertProviderConfig(
						providerName,
						configKey.name,
						value,
						configKey.secret,
					);
				}
			}
			toastSuccess({
				title: `${providerDetails.display_name} configured successfully!`,
			});
			setEditingProvider(null);
			setProviderInputs({});
			loadProviders();
		} catch (err) {
			console.error("Failed to save provider config:", err);
		}
	};

	const handleCancelEdit = () => {
		setEditingProvider(null);
		setProviderInputs({});
	};

	const handleCreateAgent = (providerName: string) => {
		const provider = availableProviders.find((p) => p.name === providerName);
		if (provider) {
			setAgentForm({
				name: "",
				model: provider.metadata.default_model,
				preamble: "You are a helpful AI assistant.",
				baseUrl: "",
				tools: [],
				apiKey: "",
			});
			setShowCreateAgent(providerName);
		}
	};

	const handleAgentFormChange = (field: string, value: string | string[]) => {
		setAgentForm((prev) => ({
			...prev,
			[field]: value,
		}));
	};

	const handleSubmitAgent = async () => {
		if (!showCreateAgent || !agentForm.name.trim()) {
			toastError({ title: "Agent name is required" });
			return;
		}

		setCreatingAgent(true);
		try {
			const newAgent = await apiService.createAgent({
				name: agentForm.name,
				provider: showCreateAgent,
				model: agentForm.model,
				preamble: agentForm.preamble,
				base_url: agentForm.baseUrl || undefined,
				tools: agentForm.tools.length > 0 ? agentForm.tools : undefined,
				api_key: agentForm.apiKey || undefined,
			});

			addAgent(newAgent);
			toastSuccess({
				title: `Agent "${agentForm.name}" created successfully!`,
			});
			setShowCreateAgent(null);
			setAgentForm({
				name: "",
				model: "",
				preamble: "You are a helpful AI assistant.",
				baseUrl: "",
				tools: [],
			});
		} catch (error) {
			console.error("Failed to create agent:", error);
			toastError({ title: "Failed to create agent" });
		} finally {
			setCreatingAgent(false);
		}
	};

	const handleCancelCreateAgent = () => {
		setShowCreateAgent(null);
		setAgentForm({
			name: "",
			model: "",
			preamble: "You are a helpful AI assistant.",
			baseUrl: "",
			tools: [],
		});
	};

	if (loading && availableProviders.length === 0) {
		return <div className="p-4 text-center">Loading providers...</div>;
	}

	return (
		<div className="p-4 space-y-6">
			<div>
				<h2 className="text-2xl font-bold">Provider Settings</h2>
				<p className="text-gray-600 dark:text-gray-400">
					Manage your LLM providers and their API configurations. Create agents
					after configuring providers.
				</p>
			</div>

			<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
				{availableProviders.map((provider) => (
					<Card key={provider.name} className="flex flex-col">
						<CardHeader>
							<CardTitle className="flex items-center justify-between">
								{provider.display_name}
								<div className="flex items-center gap-2">
									{isProviderFullyConfigured(provider.name) ? (
										<Badge variant="default" className="bg-green-500">
											Configured
										</Badge>
									) : (
										<Badge variant="secondary" className="bg-yellow-500">
											Not Configured
										</Badge>
									)}
								</div>
							</CardTitle>
							<CardDescription>{provider.metadata.description}</CardDescription>
						</CardHeader>
						<CardContent className="flex-grow flex flex-col justify-between">
							<div className="space-y-2">
								<p className="text-sm text-gray-500 dark:text-gray-400">
									<strong>Default Model:</strong>{" "}
									{provider.metadata.default_model}
								</p>
								<p className="text-sm text-gray-500 dark:text-gray-400">
									<strong>Context Limit:</strong>{" "}
									{provider.metadata.context_limit.toLocaleString()}
								</p>
								{provider.metadata.model_doc_link && (
									<a
										href={provider.metadata.model_doc_link}
										target="_blank"
										rel="noopener noreferrer"
										className="text-blue-500 hover:underline text-sm inline-block"
									>
										📖 Documentation
									</a>
								)}
								{agents.filter((a) => (a as any).provider === provider.name)
									.length > 0 && (
									<div className="mt-2">
										<p className="text-sm font-medium text-gray-700 dark:text-gray-300">
											Agents using this provider:
										</p>
										<div className="flex flex-wrap gap-1 mt-1">
											{agents
												.filter((a) => (a as any).provider === provider.name)
												.map((agent) => (
													<Badge
														key={agent.id}
														variant="outline"
														className="text-xs"
													>
														{agent.name}
													</Badge>
												))}
										</div>
									</div>
								)}
							</div>

							{editingProvider === provider.name ? (
								<div className="mt-4 space-y-3">
									{provider.metadata.config_keys.map((configKey) => (
										<div key={configKey.name}>
											<Label htmlFor={`${provider.name}-${configKey.name}`}>
												{configKey.name}{" "}
												{configKey.required && (
													<span className="text-red-500">*</span>
												)}
											</Label>
											{configKey.oauth_flow ? (
												<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
													OAuth flow not yet implemented. Please configure
													manually if possible.
												</p>
											) : (
												<Input
													id={`${provider.name}-${configKey.name}`}
													type={configKey.secret ? "password" : "text"}
													placeholder={
														configKey.default || `Enter ${configKey.name}`
													}
													value={providerInputs[configKey.name] || ""}
													onChange={(e) =>
														handleInputChange(configKey.name, e.target.value)
													}
													className="mt-1"
												/>
											)}
										</div>
									))}
									<div className="flex justify-end space-x-2 mt-4">
										<Button variant="outline" onClick={handleCancelEdit}>
											Cancel
										</Button>
										<Button onClick={() => handleSaveConfig(provider.name)}>
											Save
										</Button>
									</div>
								</div>
							) : showCreateAgent === provider.name ? (
								<div className="mt-4 space-y-3">
									<div>
										<Label htmlFor="agent-name">Agent Name *</Label>
										<Input
											id="agent-name"
											placeholder="Enter agent name"
											value={agentForm.name}
											onChange={(e) =>
												handleAgentFormChange("name", e.target.value)
											}
											className="mt-1"
										/>
									</div>
									<div>
										<Label htmlFor="agent-model">Model</Label>
										<Input
											id="agent-model"
											placeholder="Model name"
											value={agentForm.model}
											onChange={(e) =>
												handleAgentFormChange("model", e.target.value)
											}
											className="mt-1"
										/>
									</div>
									<div>
										<Label htmlFor="agent-preamble">System Prompt</Label>
										<Textarea
											id="agent-preamble"
											placeholder="Enter system prompt"
											value={agentForm.preamble}
											onChange={(e) =>
												handleAgentFormChange("preamble", e.target.value)
											}
											className="mt-1"
											rows={3}
										/>
									</div>
									<div>
										<Label htmlFor="agent-base-url">Base URL (Optional)</Label>
										<Input
											id="agent-base-url"
											placeholder="Custom API base URL"
											value={agentForm.baseUrl}
											onChange={(e) =>
												handleAgentFormChange("baseUrl", e.target.value)
											}
											className="mt-1"
										/>
									</div>
									<div>
										<Label htmlFor="agent-api-key">API Key (Optional)</Label>
										<Input
											id="agent-api-key"
											type="password"
											placeholder="Provider API key for this agent"
											value={agentForm.apiKey}
											onChange={(e) =>
												handleAgentFormChange("apiKey", e.target.value)
											}
											className="mt-1"
										/>
									</div>
									<div className="flex justify-end space-x-2 mt-4">
										<Button variant="outline" onClick={handleCancelCreateAgent}>
											Cancel
										</Button>
										<Button
											onClick={handleSubmitAgent}
											disabled={creatingAgent}
										>
											{creatingAgent ? "Creating..." : "Create Agent"}
										</Button>
									</div>
								</div>
							) : (
								<div className="mt-4 space-y-2">
									<Button
										onClick={() => handleEditClick(provider.name)}
										className="w-full"
										variant={
											isProviderFullyConfigured(provider.name)
												? "outline"
												: "default"
										}
									>
										{isProviderFullyConfigured(provider.name)
											? "Edit Configuration"
											: "Configure Provider"}
									</Button>
									{isProviderFullyConfigured(provider.name) && (
										<Button
											onClick={() => handleCreateAgent(provider.name)}
											className="w-full"
											variant="secondary"
										>
											Create Agent
										</Button>
									)}
								</div>
							)}
						</CardContent>
					</Card>
				))}
			</div>

			{availableProviders.length === 0 && !loading && (
				<div className="text-center py-8">
					<p className="text-gray-500 dark:text-gray-400">
						No providers available. Please check your configuration.
					</p>
				</div>
			)}
		</div>
	);
};

